package com.qianjiangcloud.store.activity.helpcentre;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;

import com.qianjiangcloud.store.BaseDoFragment;
import com.qianjiangcloud.store.Run;
import com.qianjiangcloud.store.http.JsonRequestBean;
import com.qianjiangcloud.store.http.JsonTask;
import com.qianjiangcloud.store.http.JsonTaskHandler;
import com.qianjiangcloud.store.util.CacheUtils;
import com.qianjiangcloud.store.util.Comm;
import com.qianjiangcloud.store.util.Util;

import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import com.qianjiangcloud.store.R;
import com.qianjiangcloud.store.libary.cache.MyImageLoader;

/**
 * 帮助详情页
 */
@SuppressLint("SetJavaScriptEnabled")
public class HelpDetailFragment extends BaseDoFragment  {

	private WebView mWebView;
	private String articleId;
	private AlertDialog mShareDialog;
	private String shareUrl;
	private String shareString;
	private String shareTitle;
	List<String> item_imgs;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mActionBar.setShowBackButton(true);
		articleId = getActivity().getIntent().getStringExtra(Run.EXTRA_ARTICLE_ID);
		shareUrl = getActivity().getIntent().getStringExtra(Run.EXTRA_DATA);
		shareTitle = getActivity().getIntent().getStringExtra(Run.EXTRA_TITLE);
		item_imgs = new ArrayList<String>();

		mActionBar.setShowHomeView(true);
		mActionBar.setTitle(shareTitle);
	}

	@Override
	public void init(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_help_detail, null);
		mWebView = (WebView) findViewById(R.id.webview);
		initWebView();
		if (articleId != null) {
			Run.excuteJsonTask(new JsonTask(), new GetArticlTask());
		}

	}


	@SuppressWarnings("deprecation")
	private void initWebView() {
		mWebView.getSettings().setBuiltInZoomControls(true);
		mWebView.getSettings().setJavaScriptEnabled(true);
		WebSettings webSettings = mWebView.getSettings();
		webSettings.setSupportZoom(true);
		webSettings.setLoadWithOverviewMode(true);
		webSettings.setUseWideViewPort(true);
//		webSettings.setTextSize(TextSize.LARGEST);
		// webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
		webSettings.setBuiltInZoomControls(false);
		// webSettings.setUseWideViewPort(true);
		// webSettings.setLoadWithOverviewMode(true);
		mWebView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				return super.shouldOverrideUrlLoading(view, url);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
//				view.loadUrl("javascript:document.body.style.webkitTextSizeAdjust='240%'");
			}
		});
	}

	class GetArticlTask implements JsonTaskHandler {

		@Override
		public void task_response(String json_str) {
			try {

				hideLoadingDialog_mt();
				JSONObject all = new JSONObject(json_str);
				if (Run.checkRequestJson(mActivity, all)) {
					JSONObject object = all.getJSONObject("data").getJSONObject("indexs");
					String value = object.optString("content");
					// 内容屏幕适配（满屏）
					pareseHtml(value);
					String newValue = "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /><style>* {max-width:100%;}* {font-size:1.0em;}</style>"
							+ value;
					mWebView.loadDataWithBaseURL(Run.MAIN_URL, newValue, "text/html", "utf-8", "");
				}
			} catch (Exception e) {
			}
		}

		@Override
		public JsonRequestBean task_request() {
			showCancelableLoadingDialog();
			return new JsonRequestBean( "mobileapi.helps.get_detail").addParams("article_id", articleId);
		}
	}

	void pareseHtml(String htmlString) {
		item_imgs.clear();
		Spanned shareSpanned = Html.fromHtml(htmlString, new ImageGetter() {

			@Override
			public Drawable getDrawable(String source) {
				// TODO Auto-generated method stub
				item_imgs.add(source);
				return null;
			}
		}, null);
		shareString = shareSpanned.toString();
		int nIndexEnter = shareString.indexOf("\n");
		if (nIndexEnter > 0) {
			shareString = shareString.substring(0, shareString.indexOf("\n"));
		}
	}

	@Override
	public void onPause() {
		try {
			mWebView.getClass().getMethod("onPause").invoke(mWebView, (Object[]) null);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
		super.onPause();
	}

	@Override
	public void onResume() {
		super.onResume();
		try {
			mWebView.getClass().getMethod("onResume").invoke(mWebView, (Object[]) null);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onClick(View v) {

	}

	public String getShareText() {
		return shareTitle;
	}

	public String getShareImageFile() {
		Bitmap bitmap = BitmapFactory.decodeResource(mActivity.getResources(), R.drawable.ic_launcher_new);
		Util.saveBitmap("share_image", bitmap);
		return Util.getPath() + "/share_image";

	}


	public String getShareImageUrl() {
		if (item_imgs != null && item_imgs.size() > 0) {
			return item_imgs.get(0);
		}

		return "";
	}


	public String getShareUrl() {
		return shareUrl;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

			return super.onKeyDown(keyCode, event);
	}

	private Handler mLoadImageHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			int remainTime = msg.what;
			remainTime += 5;
			int imgs = item_imgs.size();
			ArrayList<String> urls = new ArrayList<String>();
			if (remainTime < 60) {
				for (int i = 0; i < imgs; i++) {
					String string = CacheUtils.getImageCacheFile(item_imgs.get(i));
					File nFile = new File(string);
					if (nFile.exists()) {
						if (!TextUtils.isEmpty(string) && !urls.contains(string)) {
							urls.add(string);
						}
					} else {
					//	mVolleyImageLoader.showImage(new ImageView(mActivity), item_imgs.get(i));
						MyImageLoader.displayDefaultImage(item_imgs.get(i),new ImageView(mActivity));
					}
				}
				if (imgs == urls.size()) {
					ClipboardManager cm = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
					cm.setText(shareString);
					Comm.alert(mActivity, "文字内容已复制");
					Util.shareImagesToWx(mActivity, urls);
					hideLoadingDialog_mt();
					return;
				}
				sendEmptyMessageAtTime(remainTime + 5, 5000);
			} else {
				for (int i = 0; i < imgs; i++) {
					String string = CacheUtils.getImageCacheFile(item_imgs.get(i));
					if (!TextUtils.isEmpty(string)) {
						urls.add(string);
					}
				}
				if (urls.size() > 0) {
					ClipboardManager cm = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
					cm.setText(shareString);
					Comm.alert(mActivity, "文字内容已复制");
					Util.shareImagesToWx(mActivity, urls);
				}
				hideLoadingDialog_mt();
			}
		};
	};


}
